<?php

namespace app\common\command\task;

use app\common\exception\BusinessException;
use app\common\model\Order;
use app\common\model\OrderBonusItem;
use think\facade\Db;

/**
 *
 * php think cron orderBonusProcess
 */
class OrderBonusProcess
{

    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        $this->execute();
    }

    /**
     * execute
     * @return void
     * @throws
     */
    private function execute()
    {
        // 查询条件
        $where = [
            'is_agent' => 1,
            'is_bonus_processed' => 0,
            'status' => 4,
        ];

        // 查询数据
        $list = app(Order::class)->where($where)->field('id')->limit(10)->select();
        if (!$list) {
            echo '暂无需要处理的订单';
            return;
        }

        // 循环处理数据
        foreach ($list as $key => $item) {
            $this->executeItem($item);
        }
    }

    private function executeItem($item)
    {
        // 提取参数
        $order_id = $item['id'];

        // 开启事务
        Db::transaction(function () use ($order_id) {
            // 生成分红信息
            $orderBonusItem = new OrderBonusItem();
            $orderBonusItem->changeByOrderId($order_id);

            // 更新订单标记
            $where = ['id' => $order_id];
            $saveData = [
                'is_bonus_processed' => 1,
                'u_time' => time(),
            ];
            $isUpdate = app(Order::class)->save_data($saveData, $where);
            if (!$isUpdate) {
                throw new BusinessException('更新订单标记失败');
            }
        });
    }
}